<link rel="stylesheet" href="JQstyle.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js;"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  
<script src="lib/plugins.jquery.com-master/jquery-cookie-master/jquery.cookie.js"></script>

<link rel="stylesheet" href="style.css" />
<script>

userCountiesIds = [];
userCounties = [];


/**
/*
 * jQuery UI Multicolumn Autocomplete Widget Plugin 1.0
 * Copyright (c) 2012 Mark Harmon
 *
 * Depends:
 *   - jQuery UI Autocomplete widget
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
*/


$.widget('custom.dnautocomplete', $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
        var self = this,
            thead;
		
        if (this.options.showHeader) {
            table = $('<div class="ui-widget-header"></div>');
            $.each(this.options.columns, function(index, item) {
                table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
            });
            table.append('<div style="clear: both;"></div>');
            ul.append(table);
        }
        $.each(items, function(index, item) {
			//console.log("item "+item);
            self._renderItem(ul, item);
        });
    },
    _renderItem: function(ul, item) {
        var t = '',
            result = '';
		
        $.each(this.options.columns, function(index, column) {
            t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + 
				item[column.valueField ? column.valueField : index] + '</span>'
        });

        result = $('<li></li>')
			.data('ui-autocomplete-item', item)
			.append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>')
			.appendTo(ul);
		return result;
    }
});



$(document).ready(function(){
	
var corNc ;	
//corNc  = [{"denumire":"den1", "cod":"cod1"},{"denumire":"den2", "cod":"cod2"}]
 $.ajax({	
	url: 'includes/javascript/serverside.php',
	dataType: 'json',
	async: false,
	data: { getCorNc: '1'},
	 success: function(data) {
		corNc = data.corNc;
        }
	});
	
// Sets up the multicolumn autocomplete widget.
/*
* Autocomplete for "denumire" and asciated "cod" from cor and nc tables
* Suggests names of califications if letters are introduced in "Denumire" input field
*/
$("#corNcName").dnautocomplete({
    // These next two options are what this plugin adds to the autocomplete widget.
    showHeader: true,
	 columns: [{
        name: 'Denumire',
        width: '200px',
        valueField: 'denumire'},
    {
        name: 'Cod',
        width: '40px',
        valueField: 'cod'}],
  

    // Event handler for when a list item is selected.
    select: function(event, ui) {
		//console.log(ui);
        this.value = (ui.item ? ui.item.denumire: '');
		$('#corNcCode').val(ui.item.cod);
        return false;
    },
    // The rest of the options are for configuring the ajax webservice call.
    minLength: 1,
    source: function(request, response) {
		//console.log("corNc  : "+corNc);
		
		 var matches = $.map( corNc, function(val) {
		  if ( val.denumire.toUpperCase().indexOf(request.term.toUpperCase()) != -1 ) {
					return val;
		  }
		});
        response(matches.slice(0,12));
    }
});
/*
* Autocomplete for "cod" and assciated "denumire" from cor and nc tables
*/
$("#corNcCode").dnautocomplete({
    // These next two options are what this plugin adds to the autocomplete widget.
    showHeader: true,
	 columns: [{
		name: 'Cod',
        width: '40px',
        valueField: 'cod'
       },
    {
       name: 'Denumire',
       width: '200px',
       valueField: 'denumire' }],
  

    // Event handler for when a list item is selected.
    select: function(event, ui) {
		//console.log(ui);
        this.value = (ui.item ? ui.item.cod: '');
		$('#corNcName').val(ui.item.denumire);
        return false;
    },
    // The rest of the options are for configuring the ajax webservice call.
    minLength: 1,
    source: function(request, response) {
		//console.log("corNc ----"+corNc);
		 var matches1 = $.map( corNc, function(val) {
			 //console.log(val.cod);
			  //console.log(request.term);
		 if ( val.cod && val.cod.indexOf(request.term) != -1 ) {
			return val;
		  }
		});
        response(matches1.slice(0,12));
    }
});

/*
* Autocomplete for "denumire" and asciated "cod"
*/
$("#denumireCorNcD").dnautocomplete({
    showHeader: true,
	 columns: [{
        name: 'Denumire',
        width: '200px',
        valueField: 'denumire'},
    {
        name: 'Cod',
        width: '40px',
        valueField: 'cod'}],
  

    // Event handler for when a list item is selected.
    select: function(event, ui) {
		//console.log(ui);
        this.value = (ui.item ? ui.item.denumire: '');
		$('#codCorNcD').val(ui.item.cod);
        return false;
    },
    // The rest of the options are for configuring the ajax webservice call.
    minLength: 1,
    source: function(request, response) {
		//console.log("corNc  : "+corNc);
		
		 var matches = $.map( corNc, function(val) {
		  if ( val.denumire.toUpperCase().indexOf(request.term.toUpperCase()) != -1 ) {
					return val;
		  }
		});
        response(matches.slice(0,12));
    }
});


/*
* Checks that a string is empty
*/
function isEmpty(someVar){
	if (someVar != null && someVar != "" && someVar != " ")
		return true;
	return false;
}

/*
* String that contains the list of counties comma separated
*/	
var availableCounties = $.ajax({
   		type: "POST",
   		url: "includes/javascript/serverside.php",
  	 	data: "counties=1",
    	async: false
    }).responseText;
	


/*
*  Function that checks on blur if a CUI_CF exist in the database
*  If CUI_CF exists, a message popup appears 
*/	
 $("#CUI_CF").blur(function(event){
	 event.preventDefault();
	
	 var cui = $("#CUI_CF").val();
	 if (cui == null || cui == "" || cui == " ")
		return;
	var existentCUI = $.ajax({
	type: "POST",
	url: "includes/javascript/serverside.php",
	data: "CUI_CF="+cui+"&checkCUI=true",
	async: false
}).responseText;
    //console.log(existentCUI);
	if (existentCUI == "1"){
		showDialog();
	}
 });
/*
* Dialog box for commnet
*/	
$("#rejectComm").click(function(e) {
  e.preventDefault();
  $( "#dialogRejectComm" ).dialog({
		width: 370,
		height: 180,
		modal: true,
		title: "Comentarii",
		buttons: {
		  Ok: function() {},
		  Cancel: function(){}
		
  }
})
  return true;
  });
	
/*
* Counties autocomplete 
*/	
/*
$( "#judet_furnizor" ).autocomplete({
  source: function( request, response ) {
	
	var counties_array = new Array();
	counties_array = availableCounties.split(",");
	
    var matches = $.map( counties_array, function(tag) {
      if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
        return tag;
      }
    });
    response(matches);
  }
});
*/

/*
* Localities autocomplete
*/
$("#localitate_furnizor").autocomplete({
  source: function( request, response ) {
	
	
	var localities_array = new Array();
	//alert($("select[id=judet_furnizor] option:selected").text());
	var availableLocalities = getLocalities( $("#judet_furnizor").val() );
	
	localities_array = availableLocalities.split(",");
	
    var matches = $.map( localities_array, function(tag) {
      if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
        return tag;
      }
    });
    response(matches);
  }
});
	 
/*
* Add county to textarea in admin interface
*/

$("#addUserCountyButton").click(function() {
	var selectedCounty = $("#selectedCountyForUser").val() ;
	//alert (selectedCounty);
	if (selectedCounty != 'none')
		$("#countiesAreaAddUser").append(selectedCounty).append("\n");
	
	//var countyId = getCountyId(selectedCounty);
		
	//if ( $.inArray(countyId, userCounties) == -1)
		//userCountiesIds.push(countyId);
});

/* 
* Check that introduced email for a new user doesn't exist in Utilizatori table already
*/
$("#userEmail").blur(function(event){
	 event.preventDefault();
	
	 var userEmail = $("#userEmail").val();
	 if (userEmail == null || userEmail == "" || userEmail == " ")
		return;
	var existentUserEmail = $.ajax({
	type: "POST",
	url: "includes/javascript/serverside.php",
	data: "userEmailExists="+userEmail,
	async: false
}).responseText;
	/* 1 - an user with this email already exists in Utilizatori table
	/* 0 - this email doesn't exist in Utilizatori table yet */
	if (existentUserEmail == "1"){
		showExistentEmailDialog();
		$("#userEmail").val("");
		return false;
	}
 });
 
/*
$("#addNewUser").click( function (event){
		//event.preventDefault();
		console.log(userCounties);
		
		var stringListCounties = "";
		for (var i in userCounties)
			stringListCounties = stringListCounties + userCounties[i] + "\n";
			
		console.log(stringListCounties);	
		$.cookie('userCounties', stringListCounties);
		return true;
});
*/

//$("#countiesAreaAddUserReload").val($.cookie('userCounties'));

});

/*
* Pops up a dialog when the introduced CUI exists in BD
*/
function showDialog()
{
$( "#dialogCUI_CF" ).dialog({
		width: 370,
		height: 180,
		modal: true,
		title: "CUI/CF existent",
		buttons: {
		  Ok: function() {
		  $(this).dialog( "close" );
		}
  }
});
}

/*
* A dialog pops up if the introduced email already exists in the database
*/
function showExistentEmailDialog()
{
$( "#existentEmailDialog" ).dialog({
		width: 390,
		height: 180,
		modal: true,
		title: "Email existent",
		buttons: {
		  Ok: function() {
		  $(this).dialog( "close" );
		  }
  		}
}).css("font-size", "16px");;
}


/*
* Returns localities from given county
*/ 
function getLocalities(county){
	var localitiesInCounty = $.ajax({
	type: "POST",
	url: "includes/javascript/serverside.php",
	data: "county="+county+"&getLocalities=1",
	async: false
}).responseText;
return localitiesInCounty;
}

/*
* Returns an id for a given county or -1 if none is found
*/

function getCountyId(county){
	var countyId = $.ajax({
	type: "POST",
	url: "includes/javascript/serverside.php",
	data: "county="+county+"&getCountyId=1",
	async: false
}).responseText;
return countyId;
}
	

</script>
<?php
?>